import json
import random
import time
from urllib.parse import quote

import requests
from bs4 import BeautifulSoup
from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse
from django.views import View
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait


# Create your views here.


class StockView(View):

    def get(self, request):
        dic = {'path': request.path,
               'method': request.method}
        res = get(request.GET.get('name'))
        if res:
            result = extract_json_from_text(res)
            dic['result'] = result
            next_url = f'https://quote.eastmoney.com/unify/r/{result["market"]}.{result["code"]}'
            """无头爬取很慢"""
            # dic['price'] = get_price(next_url)
            """通过接口获取"""
            # TODO
        return HttpResponse(json.dumps(dic, ensure_ascii=False, cls=DjangoJSONEncoder))


# 模拟 header
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
}
session = requests.Session()


def get_price(next_url):
    # 1. 配置本地chromedriver路径（使用你的本地路径）
    chromedriver_path = "/Users/admin/Documents/chromedriver-mac-arm64/chromedriver"
    service = Service(executable_path=chromedriver_path)

    # 2. 配置Chrome无头模式
    chrome_options = Options()
    chrome_options.add_argument("--headless=new")  # 无头模式（Chrome 112+推荐）
    chrome_options.add_argument("--disable-gpu")
    chrome_options.add_argument("--no-sandbox")  # 解决部分环境的权限问题
    chrome_options.add_argument("--disable-dev-shm-usage")

    # 3. 启动浏览器（同时传入service和options）
    # 注意：变量名是 chrome_options，不是 options
    driver = webdriver.Chrome(service=service, options=chrome_options)

    # 4. 访问页面并操作
    try:
        driver.get(url=next_url)
        # 5. 改为等待 body（不会挂）
        WebDriverWait(driver, 15).until(
            EC.presence_of_element_located((By.TAG_NAME, "body"))
        )
        # 6. 提取渲染后 HTML
        html = driver.page_source
        soup = BeautifulSoup(html, "html.parser")
        price = soup.find('span', class_='price_down blinkgreen').text
        return price

    except Exception as e:
        print(f"操作出错：{e}")
    finally:
        driver.quit()  # 确保关闭浏览器


def get(code):
    url = f'https://search-codetable.eastmoney.com/codetable/search/web?client=web&clientType=webSuggest&clientVersion=lastest&cb={generate_jquery_like_string()}&keyword={quote(code)}&pageIndex=1&pageSize=5&securityFilter=&_={int(time.time() * 1000)}'
    response = session.get(url=url, headers=headers)
    return response.text


def generate_jquery_like_string():
    prefix = "jQuery"
    fixed_part = "1124"
    remaining_digits = ''.join(random.choices('0123456789', k=12))
    unique_id = fixed_part + remaining_digits
    timestamp = int(time.time() * 1000)
    result = f"{prefix}{unique_id}_{timestamp}"
    return result


def extract_json_from_text(res):
    start = res.find('(') + 1
    end = res.rfind(')')
    json_str = res[start:end]
    try:
        data = json.loads(json_str)
        if 'result' in data:
            return data['result'][0]
        else:
            return []

    except json.JSONDecodeError as e:
        print(f"解析JSON出错: {e}")
        return None
